package fr.sportcom.sportcom.controller;

import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.MarkerOptions;

import fr.sportcom.sportcom.R;
import fr.sportcom.sportcom.SportComApplication;
import fr.sportcom.sportcom.adapter.ComListAdapter;
import fr.sportcom.sportcom.adapter.UserListAdapter;
import fr.sportcom.sportcom.model.AdsManager;
import fr.sportcom.sportcom.model.CEvent;
import fr.sportcom.sportcom.model.Comment;
import fr.sportcom.sportcom.model.CustomHttpClient;
import fr.sportcom.sportcom.model.User;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.InputType;
import android.text.Spanned;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

//public class EventDetailActivity extends FragmentActivity implements OnTabChangeListener {
public class EventDetailActivity extends FragmentActivity implements OnCreateContextMenuListener, View.OnClickListener {

	//// EXTRA
	// En entr�e :
	public final static String EXTRA_EVENT = "fr.sportcom.sportcom.extra.EVENT";

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * current tab position.
	 */
	//private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
	public static final String TAB_GEN = "general";
	public static final String TAB_PART = "participants";
	public static final String TAB_LOC = "location";

	private ListView listView;
	private TabHost mTabHost;
	private View contentTab1;
	private CEvent selectedEvent;
	private ArrayList<User> lUserPart = new ArrayList<User>();
	private ToggleButton mButton;
	private User mLoggedUser;
	private RefreshListTask mRefresh;
	private LinearLayout mCommentView;
	private ArrayList<Comment> lComment = new ArrayList<Comment>();
	private RefreshComTask mrefreshCom = null;
	private EditText mAddCommentView = null;
	private AlertDialog mConfirm = null;
	private AddCommentTask mAddCom = null;
	private AddFriendTask mAddFriend = null;
	private subscriptionTask mSubTask = null;
	private LinearLayout mInviteBarView;

	private GoogleMap mMap;
	private LocationManager mLocationManager;
	private String mProviderName;
	private myLocationSource mLocationSourceListener = new myLocationSource();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_event_detail);
		setContentView(R.layout.sponso_layout);
		View appContent = LayoutInflater.from(this).inflate(
				R.layout.activity_event_detail, 
				(ViewGroup) this.findViewById(R.id.app_content), 
				false);
		((LinearLayout)this.findViewById(R.id.app_content)).addView(appContent);
		AdsManager.displayAds(this);

		mLoggedUser = ((SportComApplication) (this.getApplication())).getLoggedUser();

		// On r�cup�re l'intent qui a lanc� cette activit�
		Intent i = getIntent();

		// Puis les parametre donn� dans l'autre activit�
		selectedEvent = i.getParcelableExtra(EXTRA_EVENT);

		// On g�nere les onglet.
		mTabHost = (TabHost) this.findViewById(android.R.id.tabhost);
		mTabHost.setup(); // you must call this before adding your tabs!
		mTabHost.addTab(newTab(TAB_GEN, R.string.tab_gen, R.id.tab1));
		mTabHost.addTab(newTab(TAB_PART, R.string.tab_part, R.id.tab2));
		mTabHost.addTab(newTab(TAB_LOC, R.string.tab_loc, R.id.tab3));

		listView = (ListView) findViewById(R.id.listPart);

		// On integre le template.
		contentTab1 = LayoutInflater.from(this).inflate(
				R.layout.detail_read, 
				(ViewGroup) this.findViewById(R.id.tab1), 
				false);
		LinearLayout postLayout = (LinearLayout)this.findViewById(R.id.tab1);
		postLayout.addView(contentTab1);

		mCommentView = (LinearLayout) findViewById(R.id.listCom);
		mButton = (ToggleButton) findViewById(R.id.btnInscript);
		mButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				if(mSubTask == null) {
					mSubTask = new subscriptionTask();
					mSubTask.execute(mLoggedUser.getId());
				}
			}
		});
		
		mInviteBarView = (LinearLayout) findViewById(R.id.inviteBar);
		if(selectedEvent.getStatutInvite() == 0) {
			mInviteBarView.setVisibility(View.VISIBLE);
		}
		((ImageButton) findViewById(R.id.btn_accept)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.btn_refuse)).setOnClickListener(this);
		
		// On definit un menu contextuel sur la listview
		registerForContextMenu(listView);

		// On renseigne les info.
		refreshDetail();
		refreshUserList();
		refreshComList();
		initGeoloc();
		initMap();
	}

	public static PendingIntent prepareIntent(Context context, CEvent event) {
		Intent i = new Intent(context, EventDetailActivity.class);
		i.putExtra(EXTRA_EVENT, event);
		return PendingIntent.getActivity(context, 200, i, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	@Override
	public void onClick(View v) {
		inviteResponseTask responceTask = new inviteResponseTask(this);
		mInviteBarView.setVisibility(View.GONE);
		int inviteStatut = 0;
		switch(v.getId()) {
		case R.id.btn_accept:
			responceTask.execute(true);
			inviteStatut = 1;
			break;
		case R.id.btn_refuse:
			responceTask.execute(false);
			inviteStatut = -1;
		}
		selectedEvent.setStatutInvite(inviteStatut);
		refreshUserList();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_event_detail, menu);
		if(!mLoggedUser.isCreator(selectedEvent)) {
			menu.removeItem(R.id.menuItemEdit);
			menu.removeItem(R.id.menuItemInvite);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuItemEdit:
			Intent intentEvent = CreateEventActivity.prepareIntent(this, CreateEventActivity.EDIT, selectedEvent);
			this.startActivity(intentEvent);
			return true;
		case R.id.menuItemInvite:
			Intent intentFriend = FriendListActivity.prepareIntent(this, FriendListActivity.INVITE, selectedEvent.getId());
			this.startActivity(intentFriend);
			return true;
		case R.id.menuItemComment:
			if(mAddCom == null) {
				if(mConfirm == null) {
					mAddCommentView = new EditText(this);
					int inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
							InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
					mAddCommentView.setInputType(inputType);
					mConfirm = new AlertDialog.Builder(this)
					    .setTitle(R.string.add_comment_title)
					    .setView(mAddCommentView)
					    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					        public void onClick(DialogInterface dialog, int whichButton) {
								mAddCom = new AddCommentTask(EventDetailActivity.this);
								mAddCom.execute(mAddCommentView.getText().toString());
					        }
					    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					        public void onClick(DialogInterface dialog, int whichButton) {
					            // Do nothing.
					        }
					    })
					    .show();
				}
				else {
					mAddCommentView.setText("");
					mConfirm.show();
				}
			}
			return true;
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			//NavUtils.navigateUpFromSameTask(this);
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.context_menu_participant, menu);
	    boolean isCreator = mLoggedUser.isCreator(selectedEvent);
	    boolean ownerSelected = mLoggedUser.getId() == ((AdapterContextMenuInfo) menuInfo).id;
	    menu.findItem(R.id.part_context_del).setVisible(isCreator && !ownerSelected);
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    switch (item.getItemId()) {
	        case R.id.part_context_friend:
	        	if(mAddFriend == null) {
		        	mAddFriend = new AddFriendTask(this);
		        	mAddFriend.execute((int)info.id);
		            return true;
	        	}
	        	else {
	        		return false;
	        	}
	        case R.id.part_context_del:
				if(mSubTask == null) {
					mSubTask = new subscriptionTask();
					mSubTask.execute((int)info.id);
		            return true;
				}
				else {
					return false;
				}
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		AdsManager.displayAds(this);
		refreshUserList();
	}

	private TabSpec newTab(String tag, int labelId, int tabContentId) {

		View indicator = LayoutInflater.from(this).inflate(
				R.layout.tablay, 
				(ViewGroup) this.findViewById(android.R.id.tabs), 
				false);
		((TextView) indicator.findViewById(R.id.tabText)).setText(labelId);

		TabSpec tabSpec = mTabHost.newTabSpec(tag);
		tabSpec.setIndicator(indicator);
		tabSpec.setContent(tabContentId);
		return tabSpec;
	}

	private void refreshDetail() {
		DateFormat FormatDate = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE);
		DateFormat FormatHour = new SimpleDateFormat("HH:mm", Locale.FRANCE);
		String temp;

		((TextView) this.findViewById(R.id.txtSport)).setText(selectedEvent.getSport().getName());
		((TextView) this.findViewById(R.id.txtAdresse)).setText(selectedEvent.getStrAddress());
		((TextView) this.findViewById(R.id.txtDate)).setText(FormatDate.format(selectedEvent.getBegin()));
		((TextView) this.findViewById(R.id.txtbegin)).setText(FormatHour.format(selectedEvent.getBegin()));
		((TextView) this.findViewById(R.id.txtDecription)).setText(selectedEvent.getDescription());
		if(selectedEvent.isPrivate()) {
			((ImageView) findViewById(R.id.ico_private)).setVisibility(View.VISIBLE);
		}

		long dur = selectedEvent.getDuration();
		temp = dur + " min.";
		if(dur == 0) {
			temp = "-";
		}
		((TextView) this.findViewById(R.id.txtDuration)).setText(temp);

		if(dur != 0) {
			temp = FormatHour.format(selectedEvent.getEnd());
		}
		((TextView) this.findViewById(R.id.txtEnd)).setText(temp);

		int nbPart = selectedEvent.getNbparticipants();
		temp = "-";
		if(nbPart != 0) {
			temp = "" + nbPart;
		}
		((TextView) this.findViewById(R.id.txtPart)).setText("? / "+temp);
	}

	private void refreshUserList() {
		if (mRefresh != null) {
			return;
		}

		mRefresh = new RefreshListTask();
		mRefresh.link(this);
		mRefresh.execute();
	}

	private class RefreshListTask extends AsyncTask<Void, Void, Boolean> {

		private WeakReference<EventDetailActivity> mActivity = null;
		private int backStatus = -99;

		@Override
		protected Boolean doInBackground(Void... params) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+mLoggedUser.getId()));
			param.add(new BasicNameValuePair("eventId", ""+selectedEvent.getId()));
			try {
				//Thread.sleep(5000);
				jObj = request.postData("loadUserList", param);
				backStatus = jObj.getInt("back");

				if(backStatus != 0) {
					return false;
				}

				lUserPart.clear();
				JSONArray list = jObj.getJSONArray("list");
				for(int i=0; i<list.length(); i++) {
					User user = new User(list.getJSONObject(i).getInt("uti_id"), 
							list.getJSONObject(i).getString("uti_email"), 
							list.getJSONObject(i).getString("uti_prenom"), 
							list.getJSONObject(i).getString("uti_nom"), 
							list.getJSONObject(i).getString("uti_naissance"),
							list.getJSONObject(i).getString("uti_ville"),
							list.getJSONObject(i).getInt("prt_createur"),
							list.getJSONObject(i).getInt("prt_acc")
							);
					lUserPart.add(user);
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mRefresh = null;

			if (!success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue. "+backStatus, Toast.LENGTH_LONG).show();
				return;
			}

			int nbPart = selectedEvent.getNbparticipants();
			String temp = "-";
			if(nbPart != 0) {
				temp = "" + nbPart;
			}
			
			
			((TextView) mActivity.get().findViewById(R.id.txtPart)).setText(CEvent.countPart(lUserPart)+" / "+temp);
			
			UserListAdapter adapt = new UserListAdapter(mActivity.get(), lUserPart);
			listView.setAdapter(adapt);

			boolean isChecked = findId(lUserPart, mLoggedUser.getId());
			mButton.setChecked(isChecked);
			// D�activation si (on est pas le cr�ateur ou c'est un event priv� et qu'on ne parti 
			boolean isDisabled = mLoggedUser.isCreator(selectedEvent) || selectedEvent.isPrivate() && !isChecked || selectedEvent.getStatutInvite() == 0;
			//boolean isEnabled = !mLoggedUser.isCreator(selectedEvent);
			mButton.setEnabled(!isDisabled);
		}

		public void link (EventDetailActivity pActivity) {
			mActivity = new WeakReference<EventDetailActivity>(pActivity);
		}

		private boolean findId(ArrayList<User> list, int id) {
			for(int i=0; i<list.size(); i++) {
				if(list.get(i).getId() == id) {
					return true;
				}
			}
			return false;
		}
	}

	private class subscriptionTask extends AsyncTask<Integer, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... userId) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+userId[0]));
			param.add(new BasicNameValuePair("eventId", ""+selectedEvent.getId()));
			try {
				//Thread.sleep(5000);
				jObj = request.postData("subscription", param);
				int back = jObj.getInt("back");

				if(back != 0) {
					return false;
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mSubTask = null;
			refreshUserList();
		}
	}


	private class myLocationSource implements LocationSource, LocationListener {

		private OnLocationChangedListener mListener;

		@Override
		public void activate(OnLocationChangedListener listener) {
			mListener = listener;
		}

		@Override
		public void deactivate() {
			mListener = null;
		}


		@Override
		public void onLocationChanged(Location location) {
			if (mListener != null) {
				mListener.onLocationChanged(location);
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			mLocationManager.removeUpdates(this);
		}

		@Override
		public void onProviderEnabled(String provider) {
			mLocationManager.requestLocationUpdates(mProviderName, 30000, 50, this);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {}

	}

	private void initMap() {

		// Try to obtain the map from the SupportMapFragment.
		mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		// Check if we were successful in obtaining the map.
		if (mMap != null) {
			MarkerOptions markOp = new MarkerOptions();
			markOp.position(selectedEvent.getLatLngLoc())
			.title("Evénement")
			.visible(true);
			mMap.addMarker(markOp);

			mMap.moveCamera(CameraUpdateFactory.newLatLng(selectedEvent.getLatLngLoc()));


	        mMap.setLocationSource(mLocationSourceListener);
			mMap.setMyLocationEnabled(true);
		}

	}

	private void initGeoloc() {
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

		Criteria critere = new Criteria();
		// Pour indiquer la pr�cision voulue
		// On peut mettre ACCURACY_FINE pour une haute pr�cision ou ACCURACY_COARSE pour une moins bonne pr�cision
		critere.setAccuracy(Criteria.ACCURACY_FINE);
		// Est-ce que le fournisseur doit �tre capable de donner une altitude ?
		critere.setAltitudeRequired(false);
		// Est-ce que le fournisseur doit �tre capable de donner une direction ?
		critere.setBearingRequired(true);
		// Est-ce que le fournisseur peut �tre payant ?
		critere.setCostAllowed(false);
		// Pour indiquer la consommation d'�nergie demand�e
		// Criteria.POWER_HIGH pour une haute consommation, Criteria.POWER_MEDIUM pour une consommation moyenne et Criteria.POWER_LOW pour une basse consommation
		critere.setPowerRequirement(Criteria.POWER_HIGH);
		// Est-ce que le fournisseur doit �tre capable de donner une vitesse ?
		critere.setSpeedRequired(false);

		mProviderName = mLocationManager.getBestProvider(critere, true);
		mLocationManager.requestLocationUpdates(mProviderName, 30000, 50, mLocationSourceListener);
	}
	
	private class RefreshComTask extends AsyncTask<Void, Void, Boolean> {

		private WeakReference<EventDetailActivity> mActivity = null;
		private int backStatus = -99;
		
		public RefreshComTask(EventDetailActivity pActivity) {
			link(pActivity);
		}

		@Override
		protected Boolean doInBackground(Void... params) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("eventId", ""+selectedEvent.getId()));
			try {
				jObj = request.postData("loadEventCom", param);
				backStatus = jObj.getInt("back");

				if(backStatus != 0) {
					return false;
				}

				lComment.clear();
				JSONArray list = jObj.getJSONArray("list");
				for(int i=0; i<list.length(); i++) {
					
					int id = list.getJSONObject(i).getInt("com_id");
					String date = list.getJSONObject(i).getString("com_date");
					String content = list.getJSONObject(i).getString("com_contenu");
					Spanned truc = Html.fromHtml(content);
					content = truc.toString();
					String name = list.getJSONObject(i).getString("uti_nom");
					
					Comment com = new Comment(id, date, content, name);
					
					lComment.add(com);
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mrefreshCom = null;
			
			if (!success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue. "+backStatus, Toast.LENGTH_LONG).show();
			}

			/*if(lComment.size() != 0) {
				ComListAdapter adapt = new ComListAdapter(mActivity.get(), lComment);
				mCommentView.setAdapter(adapt);
			}*/
			
			if(lComment.size() != 0) {
				ComListAdapter adapt = new ComListAdapter(mActivity.get(), lComment);
				for(int i = 0; i < adapt.getCount(); i++) {
					View item = adapt.getView(i, null, null);
					mCommentView.addView(item);
				}
				((LinearLayout) findViewById(R.id.comLay)).setVisibility(View.VISIBLE);
			}
			else {
				((LinearLayout) findViewById(R.id.comLay)).setVisibility(View.GONE);
			}
		}

		public void link (EventDetailActivity pActivity) {
			mActivity = new WeakReference<EventDetailActivity>(pActivity);
		}
	}

	private void refreshComList() {
		if (mrefreshCom != null) {
			return;
		}
		mCommentView.removeAllViews();
		mrefreshCom = new RefreshComTask(this);
		mrefreshCom.execute();
	}
	

	private class AddCommentTask extends AsyncTask<String, Void, Boolean> {

		private WeakReference<EventDetailActivity> mActivity = null;
		
		public AddCommentTask(EventDetailActivity pActivity) {
			link(pActivity);
		}
		
		@Override
		protected Boolean doInBackground(String... comm) {
			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+mLoggedUser.getId()));
			param.add(new BasicNameValuePair("eventId", ""+selectedEvent.getId()));
			param.add(new BasicNameValuePair("comment", comm[0]));

			try {
				jObj = request.postData("addNewComment", param);

				if(jObj.getInt("back") != 0) {
					return false;
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAddCom = null;
			if (mActivity.get() != null) {
				if (!success) {
					Toast.makeText(mActivity.get(), "Une erreur est survenue.", Toast.LENGTH_LONG).show();
					return;
				}
				mActivity.get().refreshComList();
			}
		}
		
		public void link(EventDetailActivity pActivity) {
			mActivity = new WeakReference<EventDetailActivity>(pActivity);
		}
	}
	
	private class AddFriendTask extends AsyncTask<Integer, Void, Boolean> {

		private WeakReference<EventDetailActivity> mActivity = null;
		
		public AddFriendTask(EventDetailActivity pActivity) {
			link(pActivity);
		}
		
		@Override
		protected Boolean doInBackground(Integer... friendId) {
			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+mLoggedUser.getId()));
			for (Integer fId : friendId) {
				param.add(new BasicNameValuePair("friendId[]", ""+fId));
			}

			try {
				jObj = request.postData("addFriend", param);

				if(jObj.getInt("back") != 0) {
					return false;
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAddFriend = null;
			if (mActivity.get() != null) {
				if (!success) {
					Toast.makeText(mActivity.get(), "Une erreur est survenue.", Toast.LENGTH_LONG).show();
					return;
				}
				Toast.makeText(mActivity.get(), "Vous avez un nouvel ami.", Toast.LENGTH_SHORT).show();
			}
		}
		
		public void link(EventDetailActivity pActivity) {
			mActivity = new WeakReference<EventDetailActivity>(pActivity);
		}
	}
	
	private class inviteResponseTask extends AsyncTask<Boolean, Void, Boolean> {

		private WeakReference<EventDetailActivity> mActivity = null;
		
		public inviteResponseTask(EventDetailActivity pActivity) {
			link(pActivity);
		}
		
		@Override
		protected Boolean doInBackground(Boolean... isAccepted) {
			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+mLoggedUser.getId()));
			param.add(new BasicNameValuePair("eventId", ""+selectedEvent.getId()));
			param.add(new BasicNameValuePair("response", (isAccepted[0]?"1":"0")));

			try {
				jObj = request.postData("inviteResponse", param);

				if(jObj.getInt("back") != 0) {
					return false;
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAddFriend = null;
			if (mActivity.get() != null && !success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue.", Toast.LENGTH_LONG).show();
			}
		}
		
		public void link(EventDetailActivity pActivity) {
			mActivity = new WeakReference<EventDetailActivity>(pActivity);
		}
	}

}
